package com.hongxun.budget.ui.activity.tk;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.dialog.NoticeDialog;
import com.hongxun.budget.ui.fragment.tk.LineDeviceFragment;
import com.hongxun.budget.ui.fragment.tk.MaterialFragment;
import com.hongxun.budget.ui.fragment.tk.PhotoFragment;
import com.hongxun.budget.ui.fragment.tk.PointBasicFragment;
import com.hongxun.budget.ui.fragment.tk.QuantitiesFragment;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.budget.utils.XUtils;
import com.hongxun.greenentity.tk.DCrossCostEntity;
import com.hongxun.greenentity.tk.DPointEntity;
import com.hongxun.interfaces.ClickListener;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

public class SetMainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.radioButton2)
    RadioButton radioButton2;
    @BindView(R.id.radioButton3)
    RadioButton radioButton3;
    @BindView(R.id.radioButton5)
    RadioButton radioButton5;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.horizontalScrollView)
    HorizontalScrollView horizontalScrollView;
    int select = 0;
    Fragment pointBasic//点位信息 1
            , device//操作及设备(柱上设备) 2
            , material//部件及附件(杆塔及附件) 3
            , quantities //其他工程量 4
            , photo //拍照 5
            ;
    @BindView(R.id.right_btn)
    Button rightBtn;

    Object o;//修改时的点位
    @BindView(R.id.center_title)
    TextView centerTitle;

    @Override
    public int getLayoutId() {
        return R.layout.activity_set_main;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        rightSave.setVisibility(View.VISIBLE);
        Intent intent = getIntent();
        o = intent.getSerializableExtra("point");
        if (o != null) {//说明是修改
            rightSave.setText("修改");
            rightBtn.setVisibility(View.VISIBLE);
            rightBtn.setText("删除");
            if (o instanceof DPointEntity) {//点位修改
                SPUtils.put(context, "UUID", ((DPointEntity) o).getGuid());
                SPUtils.put(context, "point_name", ((DPointEntity) o).getPPName());
                SPUtils.put(context, "location_lat", ((DPointEntity) o).getPPAutolatitude());//定位经纬度保持不变
                SPUtils.put(context, "location_lgt", ((DPointEntity) o).getPPAutolongitude());
                SPUtils.put(context, "process", ((DPointEntity) o).getPPWorktype());
            } else if (o instanceof DCrossCostEntity) {//交叉跨越修改
                SPUtils.put(context, "UUID", ((DCrossCostEntity) o).getGuid());
                SPUtils.put(context, "point_name", "交叉跨越");
                SPUtils.put(context, "location_lat", ((DCrossCostEntity) o).getCCAutollatitude());
                SPUtils.put(context, "location_lgt", ((DCrossCostEntity) o).getCCAutollongitude());
            }
        } else {
            SPUtils.put(context, "UUID", UUID.randomUUID().toString());//进入界面直接生成点位UUID
        }
        radioGroup.setOnCheckedChangeListener(this);
        radioGroup.check(R.id.radioButton1);
        setView();
        centerTitle.setText(SPUtils.get(context, "point_name", "").toString() + "(" + SPUtils.get(context, "process", "").toString() + ")");
    }

    void setView() {
        String pointName = (String) SPUtils.get(context, "point_name", "");
        if (pointName.equals("交叉跨越")) {
            radioButton2.setVisibility(View.GONE);
            radioButton3.setVisibility(View.GONE);
        }
        if (SPUtils.get(context, "point_name", "").equals("搭火点")) {
            radioButton5.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        scrollCenter(checkedId);
        switch (checkedId) {
            case R.id.radioButton1:
                select = 0;
                break;
            case R.id.radioButton2:
                select = 1;
                break;
            case R.id.radioButton3:
                select = 2;
                break;
            case R.id.radioButton4:
                select = 3;
                break;
            case R.id.radioButton5:
                select = 4;
                break;
        }
        selecte(select);
    }

    /**
     * 设置fragment显示以及切换
     *
     * @param i
     */
    private void selecte(int i) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction, i);
        switch (i) {
            case 0:
                if (pointBasic == null) {
                    pointBasic = new PointBasicFragment();
                    ((PointBasicFragment) pointBasic).setO(o);//修改带入数据
                    fragmentTransaction.add(R.id.content, pointBasic);
                } else {
                    fragmentTransaction.show(pointBasic);
                }
                break;
            case 1:
                if (device == null) {
                    device = new LineDeviceFragment();
                    fragmentTransaction.add(R.id.content, device);
                } else {
                    fragmentTransaction.show(device);
                }
                break;
            case 2:
                if (material == null) {
                    material = new MaterialFragment();
                    fragmentTransaction.add(R.id.content, material);
                } else {
                    fragmentTransaction.show(material);
                }
                break;
            case 3:
                if (photo == null) {
                    photo = new PhotoFragment();
                    fragmentTransaction.add(R.id.content, photo);
                } else {
                    fragmentTransaction.show(photo);
                }
                break;
            case 4:
                if (quantities == null) {
                    quantities = new QuantitiesFragment();
                    fragmentTransaction.add(R.id.content, quantities);
                } else {
                    fragmentTransaction.show(quantities);
                }
                break;
        }
        fragmentTransaction.commit();
    }


    private void hideFragment(FragmentTransaction ft, int i) {
        if (pointBasic != null && i != 0)
            ft.hide(pointBasic);
        if (device != null && i != 1)
            ft.hide(device);
        if (material != null && i != 2)
            ft.hide(material);
        if (photo != null && i != 3)
            ft.hide(photo);
        if (quantities != null && i != 4)
            ft.hide(quantities);

    }


    void scrollCenter(int i) {
        RadioButton rb = findViewById(i);
        int scrollViewWidth = horizontalScrollView.getWidth();
        int rb_px = (int) rb.getX() + rb.getWidth() / 2;
        horizontalScrollView.scrollTo(rb_px - scrollViewWidth / 2, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == XUtils.CHOISE_IMG || requestCode == XUtils.CAMERA_IMG) && resultCode == RESULT_OK && data != null) {
            photo.onActivityResult(requestCode, resultCode, data);
        }
    }


    @OnClick({R.id.right_btn, R.id.right_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_btn://删除按钮
                new NoticeDialog().setMsg("是否删除该点位?").setCancelButton("取消", null).setConfirmButton("删除", new ClickListener() {
                    @Override
                    public void click() {
                        String pointName = (String) SPUtils.get(context, "point_name", "");
                        if (pointName.equals("交叉跨越"))
                            DBUtils.deleteCross(SetMainActivity.this);
                        else DBUtils.deletePoint(SetMainActivity.this);
                    }
                }).show(getFragmentManager(), "");
                break;
            case R.id.right_save://保存或修改按钮
                save();
                break;
        }
    }

    public void save() {
        if (!((PointBasicFragment) pointBasic).save()) {
            return;
        }
        ((PointBasicFragment) pointBasic).insertDB();
        if (device != null)
            ((LineDeviceFragment) device).insertDB();
        if (material != null)
            ((MaterialFragment) material).insertDB();
        if (photo != null) {
            ((PhotoFragment) photo).insertDB();
        }
        if (quantities != null) {
            ((QuantitiesFragment) quantities).insertDB();
        }
        /**
         * 保存工作内容
         */
        DBUtils.addWorkContent(context);

        T.showLong(context, "保存成功");
        finish();
    }

    public void finishSave() {
        NoticeDialog dialog = new NoticeDialog();
        dialog.setTitle("是否退出?").setMsg("您还未保存数据,是否退出该页面?").setCancelButton("退出", new ClickListener() {
            @Override
            public void click() {
                finish();
            }
        }).setConfirmButton("保存并退出", new ClickListener() {
            @Override
            public void click() {
                save();
            }
        }).show(getFragmentManager(), "");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishSave();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
